# encoding=utf8
import os
import requests
import json

from albertv0 import *
from staffInfo.config import root_path

DICTIONARY_PATH = root_path + '/spellDictionary.json'
STAFF_INFO_JSON_PATH = root_path + '/staffInfo.json'
LOCAL_HOST = 'http://www.om.com'
PRO_HOST = 'http://in2.4399om.com'
STAFF_INFO = '/hr/?r=staff/getStaff&all=1'


# cookies = {}
# cookies['PHPSESSID'] = 'osnmj4hgn0mg3fhbqb56r58a42'
# r = requests.get('http://www.om.com/assetv2/?r=test/getStaff', cookies = cookies)
# rs = r.text;
# rs = json.loads(rs)
# with open('./staffInfo.json', 'w') as json_file:
#     json_file.write(json.dumps(rs))

def update(cookie):
    """
    使用用户输入的cookie
    登陆HR系统获取最新的员工信息【包括在职&离职】
    同时对员工的信息进行加工
    补齐员工姓名拼音&首字母
    :param cookie:
    :return:
    """
    cookies = {
        'PHPSESSID': cookie
    }
    r = requests.get(PRO_HOST + STAFF_INFO, cookies=cookies)
    rs = r.text
    rs = json.loads(rs)
    rs = pre_processing(rs)
    # 重新写入到StaffInfo.json
    with open(STAFF_INFO_JSON_PATH, 'w') as json_file:
        json_file.write(json.dumps(rs))
    pass


def pre_processing(staff):
    """
    对获取到的员工数据进行预处理
    :param staff:
    :return:
    """
    tmp = []
    with open(DICTIONARY_PATH) as json_file:
        dictionary = json.load(json_file)
    for key in staff:
        t = staff[key]
        if t['Pinyin'] == '':
            t['Pinyin'] = get_spell(t['StaffName'], dictionary)
            pass
        if t['Abbreviation'] == '':
            t['Abbreviation'] = get_abbreviation(t['StaffName'], dictionary)
            pass
        tmp.append(t)
        pass
    return tmp
    pass


def get_spell(name, dictionary):
    result = ''
    for n in name:
        if n in dictionary:
            result += dictionary[n]
            pass
        else:
            # 暂时不处理
            pass
        pass
    return result
    pass


def get_abbreviation(name, dictionary):
    result = ''
    for n in name:
        if n in dictionary:
            result += dictionary[n][0]
            pass
        else:
            # 暂时不处理
            pass
        pass
    return result
    pass

